package com.wjk.kylin.core.security;

import com.alibaba.fastjson.JSONObject;
import com.wjk.kylin.core.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * The type Token util. 注意enabled参数，在filter中如果需要判断用户是否被禁用需要调用该属性
 * 暂时未启用，设置为默认值true
 */
@Component
public class TokenUtil extends AbstractTokenUtil {

	/**
	 * 权限管理
	 */
	@Autowired
	private AuthenticationManager authenticationManager;
	/**
	 * Token工具类
	 */
	@Autowired
	private TokenUtil jwtTokenUtil;

	@Override
	public UserDetails getUserDetails(String token) {
		String userDetailsString = getUserDetailsString(token);
		if (userDetailsString != null) {
			return JSONObject.parseObject(userDetailsString, AuthUser.class);
		}
		return null;
	}

	public Map<String, Object> getToken(String userName, String password) {
		// 开始授权
		final Authentication authentication = authenticationManager
				.authenticate(new UsernamePasswordAuthenticationToken(userName, password));

		SecurityContextHolder.getContext().setAuthentication(authentication);

		final UserDetails userDetails = (UserDetails) authentication.getPrincipal();

		final String token = jwtTokenUtil.generateToken(userDetails);

		AuthUser authUser = (AuthUser) userDetails;
		Map<String, Object> tokenMap = new HashMap<>();
		tokenMap.put("accessToken", token);
		tokenMap.put("expires", Constants.EXPIRATION);
		tokenMap.put("tokenType", Constants.TOKEN_TYPE_BEARER);
		tokenMap.put("userId", authUser.getId());

		return tokenMap;
	}
}